import { userTmp } from './temp.js'

export function observer(userinfo, viewDom) {
  var _storageinfo = JSON.parse(localStorage.getItem('info') || '{}')

  var _retInfo = {}
  var init = function() {
    initData(_storageinfo, _retInfo, userinfo)
    initDom(_retInfo, viewDom)
  }
  function initDom(retInfo, dom) {
    console.log(retInfo, userTmp(retInfo))
    dom.innerHTML = userTmp(retInfo)
  }
  function initData(_storageinfo, retInfo, userinfo) {
    for (var n in _storageinfo) {
      if (!userinfo[n]) {
        userinfo[n] = _storageinfo[n]
      }
    }

    for (var key in userinfo) {
      (function(k) {
        Object.defineProperty(retInfo, k, {
          get() {
            console.log('==============================get')
            return userinfo[k]
          },
          set(newValue) {
            console.log('==============================set')
            userinfo[k] = newValue
            localStorage.setItem('info', JSON.stringify(userinfo))
            // return userinfo[k]
            document.querySelector(`.__${k}`).innerHTML = newValue
          }
        })
      })(key)
    }
  }

  init()

  return _retInfo
}
